
//Copyright 1997-2009 Syrinx Development, Inc.
//This file is part of the Syrinx Web Application Framework (SWAF).
// == BEGIN LICENSE ==
//
// Licensed under the terms of any of the following licenses at your
// choice:
//
//  - GNU General Public License Version 3 or later (the "GPL")
//    http://www.gnu.org/licenses/gpl.html
//
//  - GNU Lesser General Public License Version 3 or later (the "LGPL")
//    http://www.gnu.org/licenses/lgpl.html
//
//  - Mozilla Public License Version 1.1 or later (the "MPL")
//    http://www.mozilla.org/MPL/MPL-1.1.html
//
// == END LICENSE ==
using System;
using System.Threading;

namespace Swaf
{
	/*
	/// <summary>
	/// Author: William Stacey (staceyw@mvps.org)
	/// Date: 06/10/04
	/// The Dijkstra semaphore (also called a counting
	/// semaphore) is used to control access to
	/// a set of resources. A Dijkstra semaphore
	/// has a count associated with it and each
	/// Acquire() call reduces the count. A thread
	/// that tries to Acquire() the semaphore
	/// with a zero count blocks until someone else
	/// calls Release() to increase the count.
	/// <seealso cref="http://www.fawcette.com/javapro/
	///            2002_02/magazine/features/krangaraju/"/>
	/// <seealso cref="http://www.mcs.drexel.edu/~shartley/
	///         MCS361/Lectures/designingJavaSemaphore.html"/>
	/// </summary>
	public sealed class Semaphore
	{
		#region Fields
		// Current count available.
		private int m_count;
		// Max slots in the semaphore.
		private int m_maxCount;
		// Object used for sync.
		private readonly object m_syncLock;
		// Object used for starvation sync.
		private readonly object m_starvationLock;
		#endregion

		#region Constructors
		/// <summary>
		/// Creates semaphore object with a m_maxCount
		/// and set initial count to m_maxCount.
		/// </summary>
		/// <param name="maxCount">
		/// Maximum count for the semaphore object.
		/// This value must be greater than zero.
		/// </param>
		public Semaphore(int maxCount) : this(maxCount, int.MaxValue)
		{
		}

		/// <summary>
		/// Creates semaphore object with
		/// a maximum count and initial count.
		/// </summary>
		/// <param name="maxCount">
		/// Maximum count for the semaphore object.
		/// This value must be greater than zero.
		/// </param>
		/// <param name="initialCount">
		/// Initial count for the semaphore object.
		/// This value must be zero or greater
		/// and less than or equal to maximumCount.
		/// </param>
		public Semaphore(int initialCount, int maxCount)
		{
			if ( initialCount < 0 )
				throw new 
					ArgumentOutOfRangeException("initialCount must be >= 0.");
			if ( maxCount < 1 )
				throw new ArgumentOutOfRangeException("maxCount must be >= 1.");
			if ( initialCount > maxCount)
				throw new 
					ArgumentOutOfRangeException("initialCount" + 
					" must be <= maxCount.");
			m_count = initialCount;
			this.m_maxCount = maxCount;
			m_syncLock = new object();
			m_starvationLock = new object();
		}

		#endregion

		#region Properties
		/// <summary>
		/// Gets the current available count (or slots)
		/// in the semaphore. A count of zero means that no slots
		/// are available and calls to Acquire will block until
		/// other thread(s) call Release.
		/// Example:
		/// A semaphore with a count of 2 will allow
		/// 2 more Acquire calls before blocking.
		/// </summary>
		public int count
		{
			get
			{
				lock(m_syncLock)
				{
					return m_count;
				}
			}
		}

		/// <summary>
		/// Gets the maximum count of the semaphore
		/// set during construction.
		/// </summary>
		public int maxCount
		{
			get { return m_maxCount; }
		}

		#endregion

		#region Public Methods

		/// <summary>
		/// Acquires semaphore and decrements count by 1.
		/// If count is zero, this will
		/// block indefinitely until another thread executes
		/// a Release() to increase the count.
		/// </summary>
		/// <returns>true if the call returned because
		/// the caller reacquired the lock for the
		/// specified object. This method does not return
		/// if the lock is not reacquired.</returns>
		public bool acquire()
		{
			return acquire(Timeout.Infinite);
		}

		/// <summary>
		/// Returns a value indicating if Semephore
		/// can be acquired within the timeout period.
		/// </summary>
		/// <returns>true if the lock was acquired before
		/// the specified time elapsed; otherwise, false.</returns>
		/// <exception cref="ArgumentOutOfRangeException">
		/// The value of the millisecondsTimeout parameter
		/// is negative, and is not equal to Infinite.
		/// </exception>
		public bool acquire(int millisecondsTimeout)
		{
			lock(m_syncLock)
			{
				// Use spin lock instead of an if test, to handle
				// rogue/barging threads that can enter
				// m_syncLock before a thread that was notified by a pulse.
				// That rogue thread would
				// decrease the count, then our "Pulsed" thread
				// would regain the lock and continue and
				// decrease the count to -1 which is an error.
				// The while loop/test prevents this.
				while ( m_count == 0 )
					try
					{
						if (!Monitor.Wait(m_syncLock, millisecondsTimeout))
							return false;
					}
					catch
					{
						// If we get interupted or aborted,
						// we may have been pulsed before.
						// If we just exit, that pulse would get lost and
						// possibly result in a "live" lock
						// where other threads are waiting
						// on m_syncLock, and never get a pulse.
						// Regenerate a Pulse as we consumed it.
						// Even if we did not get
						// pulsed, this does not hurt as any thread
						// will check again for m_count = 0.
						Monitor.Pulse(m_syncLock);
						// Rethrow the exception for caller.
						// Now semaphore state is same as if
						// this call never happened. Caller must
						// decide how to handle exception.
						throw;
					}
				m_count--;
				if ( m_count == 0 )
					lock(m_starvationLock) { Monitor.PulseAll(m_starvationLock); }
				return true;
			}
		}

		/// <summary>
		/// Acquires all the semaphores and brings
		/// m_count to zero. This has the effect
		/// of block other threads until we release one or more slots.
		/// <seealso cref="Acquire()"/>
		/// <seealso cref="ReleaseAll()"/>
		/// </summary>
		/// <returns>true if the acquired maxCount slots.
		/// This method does not return until
		/// all slots are acquired.</returns>
		public bool acquireAll()
		{
			// Aquires all slots or blocks for Timeout.Infinite.
			return acquireAll(Timeout.Infinite);
		}

		/// <summary>
		/// Tries to acquire (maxCount) slots
		/// in semaphore. If any single attempt to
		/// acquire a semaphore slot exceeds
		/// millisecondsTimeout, then return is false.
		/// Return is true if we acquire maxCount slots.
		/// Normally this method would be paired
		/// with the ReleaseAll method.
		/// </summary>
		/// <param name="millisecondsTimeout"></param>
		/// <returns>true if maxCount slots are acquired
		/// before the specified time elapsed;
		/// otherwise, false.</returns>
		public bool acquireAll(int millisecondsTimeout)
		{
			int slotsGot = 0;
			int elapsedMS = 0;
			DateTime start = DateTime.Now;
			int timeout = millisecondsTimeout;
			for (int i = 0; i < m_maxCount; i++)
			{
				try
				{
					if (! acquire(timeout) )
					{
						// Could not acquire all slots,
						// release any we may already have got.
						if ( slotsGot > 0 )
							release(slotsGot);
						return false;
					}
					else
					{
						elapsedMS = (int)((TimeSpan)
							(DateTime.Now - start)).TotalMilliseconds;
						timeout = millisecondsTimeout - elapsedMS;
						// Next wait will be a smaller timeout.

						if ( timeout < 0 )
							timeout = 0;
						// Next Acquire will return
						// false if we have to wait;

						slotsGot++;
						// If we get all remaining slots
						// with no timeout, we just keep going.
					}
				}
				catch
				{
					// Catch any exception during Acquire wait.
					if ( slotsGot > 0 )
						release(slotsGot);
					throw;
				}
			} // end for.
			// Count is not zero, so notify any/all starvation consumers.
			lock(m_starvationLock) { Monitor.PulseAll(m_starvationLock); }
			return true;
		}

		/// <summary>
		/// Increases the count of the semaphore object by one.
		/// </summary>
		public void release()
		{
			release(1);
		}

		/// <summary>
		/// Increases the count of the semaphore
		/// object by a specified amount.
		/// </summary>
		/// <param name="count">Amount by which the semaphore
		/// object's current count is to be increased.</param>
		/// <exception cref="ArgumentOutOfRangeException">
		/// The releaseCount must be one or greater.
		/// </exception>
		/// <exception cref="ArgumentOutOfRangeException">
		/// The releaseCount would cause
		/// the semaphore's count to exceed maxCount. 
		/// </exception>
		public void release(int releaseCount)
		{
			if ( releaseCount < 1 )
				throw new 
					ArgumentOutOfRangeException("releaseCount must be >= 1.");

			lock(m_syncLock)
			{
				if ( (m_count + releaseCount) > m_maxCount )
					throw new 
						ArgumentOutOfRangeException("releaseCount" + 
						" would cause the semaphore's count to exceed maxCount.");
				m_count += releaseCount;
				Monitor.PulseAll(m_syncLock);
			}
		}

		/// <summary>
		/// Returns indication if we could
		/// release one slot in the semaphore.
		/// </summary>
		/// <returns>true if we released
		/// one slot; otherwise false.</returns>
		public bool tryRelease()
		{
			return tryRelease(1);
		}

		/// <summary>
		/// Returns indication if we could release
		/// releaseCount slots in the semaphore.
		/// </summary>
		/// <param name="releaseCount"></param>
		/// <returns>true if we released releaseCount
		/// slots; otherwise false.</returns>
		public bool tryRelease(int releaseCount)
		{
			if ( releaseCount <= 0 )
				return false;

			lock(m_syncLock)
			{
				if ( (m_count + releaseCount) > m_maxCount )
					return false;
				else
					m_count += releaseCount;
				Monitor.PulseAll(m_syncLock);
				return true;
			}
		}

		/// <summary>
		/// Releases all remaining semaphores
		/// not currently owned. This would normally be
		/// called by a thread that previously
		/// called AcquireAll(). Note:  Be carefull when
		/// using this method as it will release
		/// all threads waiting on an Aquire method,
		/// which may or may not be what you want.
		/// An alternative would be to spin on
		/// TryRelease() until it returns false.
		/// </summary>
		public void releaseAll()
		{
			lock(m_syncLock)
			{
				m_count = m_maxCount;
				Monitor.PulseAll(m_syncLock);
				// We PulseAll instead of calling pulse
				// with exact number of times needed.
				// This can be slightly inefficient,
				// but is safe and simple.
				// See http://www.mcs.drexel.edu/~shartley/
				//   MCS361/Lectures/designingJavaSemaphore.html
			}
		}

		/// <summary>
		/// This method blocks the calling thread
		/// until the semaphore count drops to zero.
		/// A drop to zero will not be recognized
		/// if a release happens before this call.
		/// You can use this to get notified when
		/// semephore's count reaches zero.  This
		/// is also known as a "reverse-sensing" semaphore.
		/// </summary>
		public void waitForStarvation()
		{
			lock(m_starvationLock)
			{
				// We will block until count is 0.
				// We use Interlocked just to be sure
				// we test for zero correctly as we
				// are not in the m_syncLock context.
				if ( Interlocked.CompareExchange(ref m_count, 0, 0) != 0 )
					Monitor.Wait(m_starvationLock);
				// Any Exception during wait will
				// just go to caller.  Do not need to signal
				// any other threads as PulseAll(m_starvationLock) is used.
				// Also note we don't do a spin
				// while() test as we only care that 
				// count *did go to zero at some instant.
			}
		}
		#endregion
	} // class SemephoreDijkstra
*/

	/// <summary>
	/// A general purpose counting semaphore class that works in ways not directly
	/// available from the <c>System.Threading</c> namespace.
	/// </summary>
	public class Semaphore
	{
		protected ManualResetEvent m_trigger;
		protected uint m_count;
		protected object m_countLock;

		// set initial count
		public Semaphore(uint count) 
		{
			m_count = count;
			m_trigger = new ManualResetEvent(false);
			m_countLock = new object();
		}

		public uint count {get{return m_count;}}

		public void acquire() 
		{
			acquire(Timeout.Infinite, 1);
		}

		public void acquireAll()
		{
			acquire(Timeout.Infinite, -1);
		}

		public void acquireAll(int waitTime)
		{
			acquire(waitTime, -1);
		}

		public bool acquire(int waitTime)
		{
			return acquire(waitTime, 1);
		}

		private bool acquire(int waitTime, int count) 
		{
			while(true)
			{
				lock(m_countLock)
				{
					if(m_count > 0)
					{
						if(count != -1)
							m_count -= (uint)count;
						else 
							m_count = 0;
						if(m_count == 0)
							m_trigger.Reset();
						return true;
					}
				}
#if(!COMPACT_FRAMEWORK)
				if(!m_trigger.WaitOne(waitTime, false))
					return false;
#else
				try{
				m_trigger.WaitOne();
				}catch(Exception e)
				{
					string s = e.ToString();
				}
#endif
			}
		}

		public void release()
		{
			release(1);
		}

		public void release(uint count) 
		{
			lock(m_countLock)
			{
				m_count += count;
				m_trigger.Set();
			}
		}

		public void releaseAll()
		{
			lock(m_countLock)
			{
				m_count = UInt32.MaxValue;
				m_trigger.Set();
			}
		}

		public void setAbsolute(uint count)
		{
			lock(m_countLock)
			{
				m_count = count;
				if(m_count == 0)
					m_trigger.Reset();
				else
					m_trigger.Set();
			}
		}
	}


}